from django.shortcuts import render
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.contrib.auth import get_user_model, login, logout, authenticate
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenRefreshView
from .serializers import (
    UserSerializer, UserDetailSerializer, ResetPasswordSerializer,
    LoginSerializer, ResetPasswordRequestSerializer
)
from rest_framework.views import APIView
from django.contrib.auth.password_validation import get_password_validators
from django.conf import settings
from .utils import generate_token
from rest_framework.generics import GenericAPIView
from drf_spectacular.utils import extend_schema, OpenApiResponse

# Create your views here.

User = get_user_model()

@extend_schema(tags=['auth/tokens'])
class TokensView(GenericAPIView):
    """Token资源管理视图"""
    permission_classes = [permissions.AllowAny]
    serializer_class = LoginSerializer

    def post(self, request):
        """创建新token（登录）"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        email = serializer.validated_data['email']
        password = serializer.validated_data['password']
        user = authenticate(email=email, password=password)
        
        if user:
            refresh = RefreshToken.for_user(user)
            access_token = str(refresh.access_token)
            
            # 从settings中获取过期时间（天）
            from django.conf import settings
            expires_in_days = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'].days
            
            return Response({
                'access': access_token,
                'expires_in_days': expires_in_days,  # 直接返回天数
                'token_type': 'Bearer',
                'user': {
                    'id': user.id,
                    'email': user.email,
                    'username': user.username
                }
            })
        return Response(
            {'detail': '邮箱或密码错误'}, 
            status=status.HTTP_400_BAD_REQUEST
        )
    
    def delete(self, request):
        """
        删除token（登出）
        """
        try:
            # 在前端，我们会删除存储的token
            # 这里可以添加token黑名单等额外的安全措施
            return Response(status=status.HTTP_204_NO_CONTENT)
        except Exception as e:
            return Response(
                {'detail': '登出失败'}, 
                status=status.HTTP_400_BAD_REQUEST
            )

@extend_schema(tags=['auth/tokens'])
class TokensRefreshView(TokenRefreshView):
    """Token刷新视图"""
    pass

@extend_schema(tags=['auth/users'])
class UserViewSet(viewsets.ModelViewSet):
    """用户视图集"""
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]  # 明确指定权限
    
    def get_permissions(self):
        """根据不同的动作设置不同的权限"""
        if self.action in ['create', 'validation_rules', 'reset_password', 'request_reset_password']:
            return [permissions.AllowAny()]
        return [permissions.IsAuthenticated()]
    
    def get_serializer_class(self):
        if self.action in ['retrieve', 'update', 'partial_update']:
            return UserDetailSerializer
        return self.serializer_class

    def create(self, request, *args, **kwargs):
        """
        用户注册
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        refresh = RefreshToken.for_user(user)
        headers = self.get_success_headers(serializer.data)
        return Response({
            'token': str(refresh.access_token),
            'refresh': str(refresh),
            'user': serializer.data
        }, status=status.HTTP_201_CREATED, headers=headers)

    @action(detail=False, methods=['get'])
    def me(self, request):
        """获取当前用户信息"""
        serializer = UserDetailSerializer(request.user)
        return Response(serializer.data)

    @action(detail=False, methods=['post'], url_path='change-password')
    def change_password(self, request):
        """修改密码"""
        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')
        
        if not request.user.check_password(old_password):
            return Response({'detail': '原密码错误'}, status=status.HTTP_400_BAD_REQUEST)
        
        request.user.set_password(new_password)
        request.user.save()
        return Response({'detail': '密码修改成功'})

    @action(detail=False, methods=['post'], url_path='request-reset-password')
    def request_reset_password(self, request):
        """请求重置密码（发送验证码）"""
        serializer = ResetPasswordRequestSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        email = serializer.validated_data['email']
        
        # 生成并发送验证码
        from .verification import generate_verification_code, send_verification_code, save_verification_code
        
        code = generate_verification_code()
        if send_verification_code(email, code):
            save_verification_code(email, code)
            return Response({'detail': '验证码已发送到您的邮箱'})
        else:
            return Response(
                {'detail': '发送验证码失败，请稍后重试'}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    @action(detail=False, methods=['post'], url_path='reset-password')
    def reset_password(self, request):
        """重置密码（验证验证码并重置密码）"""
        serializer = ResetPasswordSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 从验证过的数据中获取用户和新密码
        user = serializer.validated_data['user']
        new_password = serializer.validated_data['new_password']
        
        # 设置新密码
        user.set_password(new_password)
        user.save()
        
        return Response({'detail': '密码重置成功'})

    @action(detail=False, methods=['get'], url_path='validation-rules')
    def validation_rules(self, request):
        """获取用户注册表单的验证规则"""
        from .serializers import UserSerializer
        serializer = UserSerializer()
        
        # 获取序列化器中的字段规则
        rules = {}
        for field_name, field in serializer.fields.items():
            if field_name == 'id':  # 跳过 id 字段
                continue
                
            field_rules = {
                'required': field.required,
                'help_text': str(field.help_text) if field.help_text else '',
            }
            
            # 添加最大长度
            if hasattr(field, 'max_length'):
                field_rules['max_length'] = field.max_length
                
            # 添加最小长度
            if hasattr(field, 'min_length'):
                field_rules['min_length'] = field.min_length
                
            # 添加其他验证器的规则
            if hasattr(field, 'validators'):
                for validator in field.validators:
                    if hasattr(validator, 'limit_value'):
                        if hasattr(validator, 'min_value'):
                            field_rules['min_length'] = validator.limit_value
                        if hasattr(validator, 'max_value'):
                            field_rules['max_length'] = validator.limit_value
            
            rules[field_name] = field_rules
            
        return Response(rules)
